package com.wanmait.teatrain.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wanmait.teatrain.entity.Menu;
import com.wanmait.teatrain.mapper.MenuMapper;
import com.wanmait.teatrain.service.MenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单权限表 服务实现类
 * </p>
 *
 * @author wanmait
 * @since 2025-10-22
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {
    @Resource
    private MenuMapper menuMapper;
    @Override
    public List<Menu> listMenuTree() {
        //查询所有的菜单
        LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.likeRight(Menu::getType,"menu");
        queryWrapper.eq(Menu::getStop,0);
        queryWrapper.orderByDesc(Menu::getSort);
        List<Menu> menus = menuMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(menus)){
            return Collections.emptyList();
        }
        //构建Map
        Map<Integer,Menu> menuMap = new HashMap<>();
        for (Menu menu : menus){
            menuMap.put(menu.getId(),menu);
        }
        //根节点集合
        List<Menu> rootMenus = new ArrayList<>();
        menus.forEach(menu -> {
            Integer parentId = menu.getParentId();
            //如果当前菜单是根菜单
            if (parentId == null || parentId == 0){
                rootMenus.add(menu);
            }
            else {
                //找出父菜单 把当前子菜单放入父菜单
                Menu parentMenu = menuMap.get(parentId);
                if (parentMenu!= null){
                    // 检查并初始化 children 集合
                    if (parentMenu.getChildren() == null) {
                        parentMenu.setChildren(new ArrayList<>());
                    }
                    parentMenu.getChildren().add(menu);
                }
            }
        });
        return rootMenus;
    }

    @Override
    public List<Integer> listAllowedMenuIds(Integer adminId) {

        List<Integer> menus = menuMapper.selectAllowMenuIds(adminId);
        return menus;
    }

    @Override
    public List<String> listPerms(Integer adminId) {
        List<Menu> menus = menuMapper.selectMenuByAdmin(adminId);
        // 1. 集合本身非空兜底（之前的修复保留）
        List<Menu> safeMenus = Optional.ofNullable(menus).orElse(Collections.emptyList());

        // 2. 新增：过滤集合中的null元素，再处理perms字段
        return safeMenus.stream()
                .filter(Objects::nonNull) // 关键修复：剔除集合中的null元素
                .map(Menu::getPerms)       // 此时元素均为非空，可安全调用方法
                .filter(perms -> perms != null && StringUtils.hasText(perms)) // 过滤perms为空的情况
                .collect(Collectors.toList());
    }
}
